#include "stdafx.h"
#include "Spreadsheet.h"
#include <iostream>

using namespace std;

int Spreadsheet::sCounter = 0;

Spreadsheet::~Spreadsheet() {
	if (mWidth > 0 && mHeight > 0) {
		for (int i = 0; i < mWidth; i++) {
			delete[]mCells[i];
		}
		delete[]mCells;
		mCells = NULL;
	}
}

void Spreadsheet::copyFromOtherSpreadsheet(const Spreadsheet& src) {
	mWidth = src.mWidth;
	mHeight = src.mHeight;
	mCells = new SpreadsheetCell*[src.mWidth];
	for (int i = 0; i < mWidth; i++) {
		mCells[i] = new SpreadsheetCell[src.mHeight];
	}
	for (int i = 0; i < mWidth; i++) {
		for (int j = 0; j < mHeight; i++) {
			mCells[i][j] = src.mCells[i][j];
		}
	}
}

Spreadsheet::Spreadsheet(int w, int h, const SpreadsheetApplication& theApp) : mTheApp(theApp) {
	mId = sCounter++;
	mWidth = w;
	mHeight = h;
	mCells = new SpreadsheetCell*[mWidth];
	for (int i = 0; i < mWidth; i++) {
		mCells[i] = new SpreadsheetCell[mHeight];
	}
}

Spreadsheet::Spreadsheet(const Spreadsheet& src) : mTheApp(src.mTheApp) {
	mId = sCounter++;
	copyFromOtherSpreadsheet(src);
}

Spreadsheet& Spreadsheet::operator=(const Spreadsheet& rhf) {
	if (this == &rhf) {
		return *this;
	}
	for (int i = 0; i < mWidth; i++) {
		delete[]mCells[i];
	}
	delete[]mCells;
	mCells = NULL;

	copyFromOtherSpreadsheet(rhf);

	return *this;
}

bool Spreadsheet::inRange(int w, int h) {
	bool ret = true;
	if (w > mWidth || h > mHeight || w < 0 || h < 0) {
		ret = false;
	}
	return ret;
}

void Spreadsheet::setCellAt(int x, int y, const SpreadsheetCell& sprCell) {
	if (inRange(x, y)) {
		mCells[x][y] = sprCell;
	} else {
		throw out_of_range("out of range of referenced SpreadsheetCell object");
	}
}

SpreadsheetCell Spreadsheet::getCellAt(int x, int y) {
	if (inRange(x, y)) {
		return mCells[x][y];
	} else {
		throw out_of_range("out of range of referenced SpreadsheetCell object");
	}
}

void Spreadsheet::display() {
	cout << "Hieu\n";
}



